using Microsoft.AspNetCore.Mvc;
using Beauty.Net.MongoDB.Core;
using MongoDB.Driver;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Linq.Expressions;

namespace Beauty.NetWebApi.Controllers
{
    /// <summary>
    /// MongoDB 演示控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MongoDBDemoController : ControllerBase
    {
        private readonly IMongoDBService _mongoDBService;
        private readonly ILogger<MongoDBDemoController> _logger;

        public MongoDBDemoController(IMongoDBService mongoDBService, ILogger<MongoDBDemoController> logger)
        {
            _mongoDBService = mongoDBService;
            _logger = logger;
        }

        /// <summary>
        /// 插入单个文档
        /// </summary>
        [HttpPost("insert")]
        public async Task<IActionResult> InsertOne([FromQuery] string collectionName, [FromBody] dynamic document)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                return BadRequest(new { message = "集合名称不能为空" });
            }

            await _mongoDBService.InsertOneAsync(document, collectionName);
            _logger.LogInformation("文档插入成功: {CollectionName}", collectionName);
            return Ok(new { message = "文档插入成功" });
        }

        /// <summary>
        /// 查询文档列表
        /// </summary>
        [HttpGet("list")]
        public async Task<IActionResult> GetList([FromQuery] string collectionName, [FromQuery] int limit = 10)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                return BadRequest(new { message = "集合名称不能为空" });
            }

            var collection = _mongoDBService.GetCollection<dynamic>(collectionName);
            var documents = await collection.Find(_ => true).Limit(limit).ToListAsync();
            
            return Ok(new { message = "文档查询成功", count = documents.Count, data = documents });
        }

        /// <summary>
        /// 更新文档
        /// </summary>
        [HttpPut("update")]
        public async Task<IActionResult> Update([FromQuery] string collectionName, [FromQuery] string id, [FromBody] dynamic updateData)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                return BadRequest(new { message = "集合名称不能为空" });
            }
            if (string.IsNullOrEmpty(id))
            {
                return BadRequest(new { message = "文档ID不能为空" });
            }

            var collection = _mongoDBService.GetCollection<dynamic>(collectionName);
            var filter = Builders<dynamic>.Filter.Eq("_id", id);
            var dict = updateData as IDictionary<string, object>;
            if (dict == null)
            {
                return BadRequest(new { message = "更新数据格式不正确" });
            }
            var updateBuilder = Builders<dynamic>.Update;
            var updateDefs = dict.Select(kvp => updateBuilder.Set(kvp.Key, kvp.Value));
            var update = updateBuilder.Combine(updateDefs);
            
            var result = await collection.UpdateOneAsync(filter, Builders<dynamic>.Update.Combine(update));
            _logger.LogInformation("文档更新成功: {CollectionName}, {DocumentId}", collectionName, id);
            
            return Ok(new { message = "文档更新成功", matchedCount = result.MatchedCount, modifiedCount = result.ModifiedCount });
        }

        /// <summary>
        /// 删除文档
        /// </summary>
        [HttpDelete("delete")]
        public async Task<IActionResult> Delete([FromQuery] string collectionName, [FromQuery] string id)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                return BadRequest(new { message = "集合名称不能为空" });
            }
            if (string.IsNullOrEmpty(id))
            {
                return BadRequest(new { message = "文档ID不能为空" });
            }

            var collection = _mongoDBService.GetCollection<dynamic>(collectionName);
            var filter = Builders<dynamic>.Filter.Eq("_id", id);
            var result = await collection.DeleteOneAsync(filter);
            
            _logger.LogInformation("文档删除成功: {CollectionName}, {DocumentId}", collectionName, id);
            return Ok(new { message = "文档删除成功", deletedCount = result.DeletedCount });
        }
    }
}